package com.zp.ojcodesandbox.controller;

import cn.hutool.http.server.HttpServerRequest;
import cn.hutool.http.server.HttpServerResponse;
import com.zp.ojcodesandbox.DockerCodeSandBox;
import com.zp.ojcodesandbox.JavaNativeCodeSandBox;
import com.zp.ojcodesandbox.model.ExecuteCodeRequest;
import com.zp.ojcodesandbox.model.ExecuteCodeSandResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController("/")
public class MainController {
    private static final String AUTH_REQUEST_HEADER = "auth";
    // 增加安全性
    private static final String AUTH_SECRET_KEY = "DJASDIU2903UER0FJW0FDNXSJCFVBDSIF28938"; // SECRETKEY
    @Resource
    private DockerCodeSandBox dockerCodeSandBox;

    @GetMapping("health")
    public String healthCheck(){
        return "ok";
    }

    @PostMapping("/executeCode")
    public ExecuteCodeSandResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request,
                                               HttpServletResponse response){
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        if(!AUTH_SECRET_KEY.equals(authHeader)){
            response.setStatus(403);
            return null;
        }
        if(executeCodeRequest == null){
           throw new RuntimeException("请求参数不存在");
        }else {
            return dockerCodeSandBox.executeCode(executeCodeRequest);
        }
    }
}
